﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using BOL;
using System.Data.Linq;
using System.Data.SqlClient;
using Website.Logger;
using UtilityExtensions;
using System.Drawing;

namespace UILGestion.ObraAdmin.EstructuraCompras
{
    public partial class EstructuraCostoListForm : System.Web.UI.Page
    {
        public EstructuraCostoListForm()
        {
            bol = new EstructuraCostoBL();
        }
        private EstructuraCostoBL bol;

          protected string editarEstructura(object value)
        {

            string script;
            
            script = String.Format("<script languaje=\"javascript\">var opciones=(\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=750,height=350\");" +
                      "window.open(\"EstructuraCostoEditForm.aspx?id=" + value + "\",\"\",opciones,true);" +
                      "</script>");
            
            //return "javascript:abrir_ventana(" + value + ")";
            return "EstructuraCostoEditForm.aspx?id=" + value + "&idObra=" + idObra.Value;

            //ClientScript.RegisterStartupScript(this.GetType(), "Recursos", script);

            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                try
                {
                    idObra.Value = (string)Request.QueryString["idObra"];
                    menuObraCtrl1.loadMenu(int.Parse(idObra.Value), Request.AppRelativeCurrentExecutionFilePath);
                    FormatForm();


                }
                catch (SqlException sqlex)
                {
                    WebServerSideSqlError.Log(sqlex);

                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


                }
                catch (Exception ex)
                {
                    WebServerSideError.Log(ex);
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

                }


            }
        }

        private void resetEmpty()
        {
            if (estructuraGridView.Rows.Count == 0)
            {
                List<EstructuraCostoListInfo> itemList0 = new List<EstructuraCostoListInfo>();
                EstructuraCostoListInfo itemcero = new EstructuraCostoListInfo();
                itemcero.moneda = DbUtil.Db.Monedas.Single(p => p.idInternal == 3);

                itemList0.Add(itemcero);
                estructuraGridView.DataSource = itemList0;
                estructuraGridView.DataBind();
                estructuraGridView.Rows[0].Visible = false;
            }

        }

        private void DataBindItem()
        {
            EstructuraCostoBL bol = new EstructuraCostoBL();
            int estructura=int.Parse(EstructuraDropDownList.SelectedValue);

            estructuraGridView.DataSource = bol.GetEstructuraCosto(int.Parse(idObra.Value), estructura);
            

            
            if (this.bitSameEstructura.Value == "1")
            {
                
                estructuraGridView.ShowFooter = false;
                estructuraGridView.Columns[6].Visible = false;
                estructuraGridView.Columns[7].Visible = false;
                estructuraGridView.DataBind();
            }
            else
            {
                estructuraGridView.Columns[6].Visible = true;
                estructuraGridView.Columns[7].Visible = true;
                estructuraGridView.DataBind();
                resetEmpty();
                setFooterRow();
            }


            if (EstructuraDropDownList.SelectedValue == "0")
            {
                estructuraGridView.FooterRow.Visible = false;
            }

        }
        private void FormatForm()
        {
            ShowAllComboBox();
            //restricionesForm();

            bool bitSameEstructura= DbUtil.Db.Obras.Single(p=>p.idInternal==idObra.Value.ToInt()).TipoObra.bitSameEstructura.Value;
            this.bitSameEstructura.Value= bitSameEstructura.ToInt().ToString();
            if (bitSameEstructura)
            {
                EstructuraDropDownList.Visible = false;
                EstructuraDropDownList.SelectedValue = "4";
            }
            

            DataBindItem();
            setEstadistica();

         
   //         string Lang = "es-ES";  //para controlar el idioma 
   //         System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo
   //(Lang);

           // setFooterRow();

            //ImportPresupuestoLinkButton.OnClientClick =
            //    WindowPresupuesto.GetShowReference("../Admin/PresuImportForm.aspx", "Importacion Presupuesto");
        }
        protected void ShowAllComboBox()
        {
            EstructuraDropDownList.DataTextField = "descripcion";
            EstructuraDropDownList.DataValueField = "idInternal";
            EstructuraDropDownList.DataSource =new ListValueBL().GetEstructura();
            EstructuraDropDownList.DataBind();


        

        }
        private void setFooterRow()
        {
            
            //DropDownList monedaDropDownList = ((DropDownList)proveedorGridView.FooterRow.FindControl("monedaInsertDropDownList"));
            
            //DropDownList obraInsertDropDownList =
            //    ((DropDownList)estructuraGridView.FooterRow.FindControl("Estructura2DropDownList"));


            //obraInsertDropDownList.DataValueField = "idInternal";
            //obraInsertDropDownList.DataTextField = "descripcion";
            //obraInsertDropDownList.DataSource = DbUtil.Db.Estructuras;
            //obraInsertDropDownList.DataBind();




        }

        protected void itemGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((EstructuraCostoListInfo)e.Row.DataItem != null)
                {
                    var a = (EstructuraCostoListInfo)e.Row.DataItem;
                    //para ambos casos 
                    e.Row.Cells[4].ForeColor = (a.montoBase - a.montoOCUso <= -0.99m) ? Color.Red : Color.Green;
                   


                }
            }
        }
        protected void gvestructura_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridView gv = (GridView)e.Row.FindControl("recursoEGridView");

            //    gv.DataSource = new EstructuraCostoBL().GetRecursoEstructuraCostoItem((e.Row.DataItem as EstructuraCostoListInfo).idInternal);
            //    gv.DataBind();
            //}
        }



        protected void onSelectChanged(object sender, EventArgs e)
        {
            try
            {
                this.DataBindItem();  
                
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void cargaRecursos_click(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkdivrecurso = (ImageButton)sender;
                int idEC=int.Parse(lnkdivrecurso.CommandName);
                int rowindex=int.Parse(lnkdivrecurso.CommandArgument);
                string div="div"+idEC.ToString();
                string script = String.Empty;

                Panel divcol = (Panel)estructuraGridView.Rows[rowindex].FindControl("divgrilla");

                if (lnkdivrecurso.ImageUrl == "../../Images/expand_button.png")
                {
                    GridView gv = (GridView)estructuraGridView.Rows[rowindex].FindControl("recursoEGridView");
                UpdatePanel panel = (UpdatePanel)estructuraGridView.Rows[rowindex].FindControl("recursoUpdatePanel");
                   
                   
                        
                gv.DataSource = new EstructuraCostoBL().GetRecursoEstructuraCostoItem(idEC);
                gv.DataBind();

                lnkdivrecurso.ImageUrl = "../../Images/expand_button_down.png";
                   divcol.Style.Add("display","inline");

              
          

                panel.Update();
                }else
                {
                   lnkdivrecurso.ImageUrl = "../../Images/expand_button.png";
                  divcol.Style.Add("display", "none");
                }


               
                
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        

        protected void actualizarButton_Click(object sender, EventArgs e)
        {

            DataBindItem();
            setEstadistica();
        }

        private void setEstadistica()
        {
            var obra = DbUtil.Db.Obras.Single(p => p.idInternal == int.Parse(idObra.Value));
            EstructuraCostoBL bol= new EstructuraCostoBL();
            EstructurCostoTotalInfo info = bol.GetEstructuraCostoTotales(obra);
            totalPresupuestoLabel.Text = info.presupuestoSoles;
            totalPresupuestoDLLLabel.Text = info.presupuestoDollar;
            estructuraCostoLabel.Text = info.estructuraItemSoles;
            estructuraCostoDLLLabel.Text =info.estructuraItemDollar;
            totalOCDLLLabel.Text =info.estructuraItemUsoDollar ;
            totalOCLabel.Text = info.estructuraItemUsoSoles ;
            totalSaldoSolLBL.Text = info.estructuraSaldoSoles;
            totalSaldoDolLBL.Text = info.estructuraSaldoDollar;
            totalesPanel.GroupingText=string.Format("Tipo de Cambio Obra: {0:N3}",obra.tipoCambio.Value);
            totalesUpdatePanel.Update();
                         
        }
        protected void nuevoButton_Click(object sender, EventArgs e)
        {

            estructuraGridView.FooterRow.Visible = true;
             ///Response.Redirect("PresupuestoAdicionInsertForm.aspx?idObra=" + idObra.Value, true);
        }
        protected void AddLinkButton_onClick(object sender, EventArgs e)
        {


            if (((Button)sender).ID == "addProvAdd")
            {
                dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString);
                string descripcion = ((TextBox)estructuraGridView.FooterRow.FindControl("descripcionEditTextbox")).Text;

                bol.add(_db,descripcion, int.Parse(idObra.Value), int.Parse(EstructuraDropDownList.SelectedValue),false);

                DataBindItem();
                estructuraUpdate.Update();
            }
            if (((Button)sender).ID == "cancelLinkButton")
            {
                estructuraGridView.FooterRow.Visible = false;
                ((TextBox)estructuraGridView.
                    FooterRow.FindControl("descripcionEditTextbox")).Text="";
            }

         

        }

        protected void Deleteitem(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkRemove = (ImageButton)sender;

                EstructuraCostoBL estructura = new EstructuraCostoBL();
                estructura.delete( int.Parse(lnkRemove.CommandArgument.ToString()));
                DataBindItem();
                setEstadistica();
                estructuraUpdate.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                estructuraGridView.EditIndex = e.NewEditIndex;


                int parent_index = e.NewEditIndex;
                DataBindItem();
                ////GridViewRow row = GridView1.Rows[parent_index];
                DropDownList ddl =
                        ((DropDownList)estructuraGridView.Rows[parent_index].FindControl("Estructura2DropDownList"));

                TextBox txt =
                        ((TextBox)estructuraGridView.Rows[parent_index].FindControl("Estructura2TextBox"));

                ddl.DataTextField = "descripcion";
                ddl.DataValueField = "idInternal";
               
                ddl.DataSource = DbUtil.Db.Estructuras;
                ddl.DataBind();
                ddl.SelectedValue = txt.Text;

                estructuraGridView.FooterRow.Visible = false;

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                string idInternal = ((GridView)sender).DataKeys[e.RowIndex].Values[0].ToString();

               string descripcion = ((TextBox)estructuraGridView.Rows[e.RowIndex].FindControl("descripcionEditTextBox")).Text;
               DropDownList ddl =
                      ((DropDownList)estructuraGridView.Rows[e.RowIndex].FindControl("Estructura2DropDownList"));


                dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString);
                EstructuraCosto EC = _db.EstructuraCostos.Single(p => p.idInternal == int.Parse(idInternal));

                EC.descripcion = descripcion;
                EC.idPadre = int.Parse(ddl.SelectedValue);
                _db.SubmitChanges();
                estructuraGridView.EditIndex = -1;
                DataBindItem();
                estructuraUpdate.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        protected void editEcostoButton_click(object sender, EventArgs e)
        {
            int idInternal = int.Parse(((LinkButton)sender).CommandArgument.ToString());
            Response.Redirect("EstructuraCostoEditForm.aspx?idObra=" + idObra.Value + "&id=" + idInternal.ToString());
            


        }


        protected void CancelEditItem(object sender, GridViewCancelEditEventArgs e)
        {
            estructuraGridView.EditIndex = -1;
            DataBindItem();
            estructuraUpdate.Update();
            
        }

        
    }
}